#include "UsrAI.h"
#include<set>
#include <iostream>
#include<unordered_map>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
tagInfo info;
int builddock=0;
int beginx = 0;
int beginy = 0;
static int stage=1;
static int center_x=0;
static int center_y=0;
static int homePositions[4][2] = {0}; // 存储4个房屋的块坐标
static int homesnumber = 0; // 已建造的房屋数量
bool home_flag = false;
//
//
double calculateDistance(double x1, double y1, double x2, double y2) {           //计算资源距离
    double dx = x1 - x2;
    double dy = y1 - y2;
    return sqrt(dx*dx + dy*dy);
}
int findResource(const tagInfo& info, int targetType, double workerDR, double workerUR) {   //找寻该资源最近位置
    int bestSN = -1;
    double min =10000;

    for (const auto& resource:info.resources) {
        if (resource.Type != targetType) {
            continue;
        }
        bool beoccupied = false;        //检查有没有村民在进行占用
        for (const auto& farmer:info.farmers) {
            if (farmer.WorkObjectSN == resource.SN && farmer.NowState == HUMAN_STATE_WORKING) {
                beoccupied = true;
                break;
            }
        }
        if (beoccupied) {
            continue;
        }
        double distance = calculateDistance(workerDR, workerUR, resource.DR, resource.UR);
        if (distance < min) {
            min = distance;
            bestSN = resource.SN;
        }
    }

    return bestSN;
}

char themap[128][128];
int find_block(int beginx1,int beginy1,int& x, int& y)
{
    for (int i = beginx1+1; i < 128; i++) {
        for (int j = beginy1+1; j < 128; j++) {
            if (i + 1 < 128 && j + 1 < 128) {
                // 检查四个位置是否都是陆地
                if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i][j + 1].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_GRASS) {
                    // 检查高度是否相等
                    int height = (*info.theMap)[i][j].height;
                    if ((*info.theMap)[i + 1][j].height == height &&
                        (*info.theMap)[i][j + 1].height == height &&
                        (*info.theMap)[i + 1][j + 1].height == height) {
                        if(themap[i][j]!='*'&&themap[i+1][j]!='*'&&themap[i][j+1]!='*'&&themap[i+1][j+1]!='*'&&themap[i][j]!='H'&&themap[i+1][j]!='H'&&themap[i][j+1]!='H'&&themap[i+1][j+1]!='H'){
                        // 找到符合条件的2*2空地，返回左下角坐标
                        x = i-1;
                        y = j;

                        return 1; // 返回1表示成功找到
}
                    }
                }
            }
        }
    }
    return 0; // 返回0表示未找到合适的空地
}
int find_block_dock(int& x, int& y)
{
    for (int i=0; i < 128; i++) {
        for (int j=0; j < 128; j++) {
            if (i+1 < 128 && j + 1 < 128) {
                // 检查四个位置是否都是陆地
                if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN &&
                    (*info.theMap)[i+1][j].type == MAPPATTERN_OCEAN &&
                    (*info.theMap)[i][j+1].type == MAPPATTERN_OCEAN &&
                    (*info.theMap)[i+1][j+1].type == MAPPATTERN_OCEAN){

                    // 检查高度是否相等
                    if (((*info.theMap)[i+2][j].type == MAPPATTERN_GRASS &&(*info.theMap)[i+2][j+1].type == MAPPATTERN_GRASS) ||
                        ((*info.theMap)[i-1][j].type == MAPPATTERN_GRASS &&(*info.theMap)[i-1][j+1].type == MAPPATTERN_GRASS) ||
                        ((*info.theMap)[i][j-1].type == MAPPATTERN_GRASS &&(*info.theMap)[i+1][j-1].type == MAPPATTERN_GRASS) ||
                        ((*info.theMap)[i][j+2].type == MAPPATTERN_GRASS && (*info.theMap)[i+1][j+2].type == MAPPATTERN_GRASS ))
                    {
                        // 找到符合条件的2*2空地，返回左下角坐标
                        x = i;
                        y = j;
                          cout<<x<<" "<<y<<endl;
                       return 1; // 返回1表示成功找到

                    }
                }
            }
        }
    }
    return 0; // 返回0表示未找到合适的空地
}

void UsrAI::processData()
{
    info=getInfo();
    std::vector<tagFarmer>idleFarmer;               // 存储闲置的农民
    std::vector<tagFarmer>fishingFarmer;            // 存储捕鱼的农民
    std::vector<tagFarmer>cuttingFarmer;            // 存储砍树的农民
    std::vector<tagFarmer>buildingHomeFarmer;      // 存储建造房子的农民
    std::vector<tagFarmer>huntingFarmer;            // 存储抓羊的农民
    std::vector<tagBuilding>homenumber;             // 存储房子数量
    std::vector<tagBuilding>stocknumber;             // 存储仓库数量
    std::vector<tagBuilding>docknumber;             // 存储船坞数量
    std::vector<pair<int,int>>builtpositions;
    std::map<int,tagResource> SN_to_Resource;
    std::map<int,int>SN_to_Sort;
    for(tagResource resource:info.resources) {
            SN_to_Resource[resource.SN] = resource;
            SN_to_Sort[resource.SN] = resource.Type;
        }
    for(tagBuilding building:info.buildings) {
            if(building.Type == BUILDING_HOME) homenumber.push_back(building);
            if(building.Type == BUILDING_STOCK) stocknumber.push_back(building);
            if(building.Type == BUILDING_DOCK) docknumber.push_back(building);
        }
    for(tagFarmer farmer:info.farmers) {
        if(farmer.FarmerSort == 0){
          if(farmer.NowState == HUMAN_STATE_IDLE ) idleFarmer.push_back(farmer);  // 将闲置农民加入数组
          if(farmer.NowState == HUMAN_STATE_WORKING){
            int Type = SN_to_Sort[farmer.WorkObjectSN];
            // 状态对应
            if(Type == RESOURCE_TREE) cuttingFarmer.push_back(farmer);
            if(Type == RESOURCE_FISH) fishingFarmer.push_back(farmer);
            if(Type == BUILDING_HOME) buildingHomeFarmer.push_back(farmer);
            if(Type == RESOURCE_GAZELLE) huntingFarmer.push_back(farmer);
          }
        }
    }


        for(int x=0;x<128;x++)
        {
            for(int y=0;y<128;y++)
            {
                int nowtype=(*info.theMap)[x][y].type;
                if(nowtype==MAPPATTERN_UNKNOWN)
                {
                    themap[x][y]='?';                //未探索区域
                }
                if(nowtype==MAPPATTERN_OCEAN)
                {
                    themap[x][y]='-';
                }
                else
                {
                    int height=(*info.theMap)[x][y].height;
                    themap[x][y]='0'+height;
                }
            }
        }
        for(int i=0;i<(int)info.resources.size();i++)
        {
            if(info.resources[i].Type==RESOURCE_FISH)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='f';                        //fish
            }
            if(info.resources[i].Type==RESOURCE_TREE)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='t';                        //tree
            }
            if(info.resources[i].Type==RESOURCE_GAZELLE)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='g';                        //fazelle
            }
            if(info.resources[i].Type==RESOURCE_GOLD)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='$';                        //gold
            }
            if(info.resources[i].Type==RESOURCE_STONE)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='s';                        //stone
            }
            if(info.resources[i].Type==RESOURCE_ELEPHANT)
            {
                int x=info.resources[i].BlockDR;
                int y=info.resources[i].BlockUR;
                themap[x][y]='e';                        //elephant
            }
        }
        for(int i=0;i<(int)info.farmers.size();i++)
        {
            themap[info.farmers[i].BlockDR][info.farmers[i].BlockUR]='*';
        }




    switch(stage)
 {
case 1://阶段一：重点采集资源以及造人建房子
    {
        // 在阶段1中，找到市镇中心后初始化房屋位置
        for (tagBuilding& building : info.buildings) //如果市镇中心空闲，且有足够的食物，且农民数量小于人口上限，则生产农民
        {
               if (building.Type == BUILDING_CENTER && building.Project == 0 && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD &&
                       info.farmers.size() < info.Human_MaxNum) {
                   BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);}
               if (building.Type == BUILDING_DOCK && building.Project==0 && info.Wood >=BUILDING_DOCK_CREATE_SAILING_WOOD && docknumber.size()<2)
                   BuildingAction(building.SN,BUILDING_DOCK_CREATE_SAILING);
                   break;

           }
        for (tagBuilding building : info.buildings) {
            if (building.Type == BUILDING_CENTER) {
                center_x = building.BlockDR+1; // 市镇中心中心坐标
                center_y = building.BlockUR+1;
            }
        }
        if(beginx==0 && beginy==0)
        {
            beginx=center_x;
            beginy=center_y;
        }
        if (homenumber.size() < 4) {
                    int targetx = 0, targety = 0;

                    // 尝试找到合适的空地
                    if (find_block(beginx, beginy, targetx, targety) == 1) {
                        // 检查是否已有足够的木材
                        if (info.Wood >= BUILD_HOUSE_WOOD && !idleFarmer.empty()) {
                            // 命令第一个闲置村民建造房屋
                            for (tagFarmer& farmer : idleFarmer) {
                                if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0)
                                HumanBuild(farmer.SN, BUILDING_HOME, targetx, targety);
                                for (int i = 0; i < 2; i++) {
                                for (int j = 0; j < 2; j++) {
                                themap[targetx + i][targety + j] = 'H'; // 标记为房屋
                            }
                             }
                            }
                        }
                        beginx=targetx;
                        beginy=targety;
                    }

                }

        //进行各种资源的搜集
          if(homenumber.size()>=4)
          {
             if(huntingFarmer.size()<4){
              int targetSN=-1;
              for (tagFarmer& farmer : info.farmers) {
                      if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0) {
                          targetSN = findResource(info,RESOURCE_GAZELLE, farmer.DR, farmer.UR);
                          HumanAction(farmer.SN, targetSN);
                          }
              }
              }
             else{
                 if(docknumber.size()<1)         //先找一个人去建船舱
                 {
                     int buildx=0;
                     int buildy=0;
                     if(find_block_dock(buildx,buildy)==1)
                    {
                            for (tagFarmer& farmer : idleFarmer)
                            HumanBuild(farmer.SN,BUILDING_DOCK,buildx,buildy);
                                     }
                 }
                 int targetSN=-1;
                 //剩下的人去砍树
                 for (tagFarmer& farmer : info.farmers) {
                         if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0 &&cuttingFarmer.size()<4) {
                             targetSN = findResource(info,RESOURCE_TREE, farmer.DR, farmer.UR);
                             HumanAction(farmer.SN, targetSN);
                         }
                 }
                 int targetSN1=-1;
                 for (tagFarmer& farmer : info.farmers) {
                         if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 2 ) {
                             targetSN1 = findResource(info,RESOURCE_FISH, farmer.DR, farmer.UR);
                             HumanAction(farmer.SN, targetSN1);
                         }
                 }

                 /*if(buildstock==0)
                 {
                     if(info.Wood>150)              //检测到树木数量大于150，去建个仓库
                     {
                         int SN=findResource(info,RESOURCE_GAZELLE,farmer.DR,farmer.UR)

                         HumanBuild(farmer.SN, BUILDING_STOCK, target_x, target_y);
                         buildstock++;
                     }
                 }*/

                 }
          }
     }
 }
}
